using MultiAgentsShared;
using Windows.ApplicationModel.DataTransfer;
using Windows.Storage;

namespace MultiAgentsClient.Presentation.Component;

public sealed partial class ChatInputBox : UserControl
{
    private readonly EventBus eventBus;

    public record AddFileCommand(List<string> FilePath);

    public ChatInputBox()
    {
        InitializeComponent();

        DataContext = new BindableChatInputBoxModel();

        eventBus = EventBus.Instance;
    }

    private void OnTextBoxKeyDown(object sender, Microsoft.UI.Xaml.Input.KeyRoutedEventArgs e)
    {
        var dataContext = (BindableChatInputBoxModel)DataContext;

        if (dataContext.IsShiftKeyDown == true && e.Key == Windows.System.VirtualKey.Enter)
        {
            TextBox? textBox = sender as TextBox;
            int cursorPosition = textBox?.SelectionStart ?? throw new Exception("This should not happen");
            textBox.Text = textBox.Text[..cursorPosition] + "\r" + textBox.Text[cursorPosition..];
            MessageTextBox.SelectionStart = cursorPosition + 1;
        }
    }

    private void OnTextBoxKeyUp(object sender, Microsoft.UI.Xaml.Input.KeyRoutedEventArgs e)
    {
        var dataContext = (BindableChatInputBoxModel)DataContext;
        if (e.Key == Windows.System.VirtualKey.Tab && dataContext.IsShiftKeyDown == false)
        {
            MessageTextBox.SelectionStart = MessageTextBox.Text.Length;
        }
        else if (e.Key == Windows.System.VirtualKey.Shift)
        {
            dataContext.IsShiftKeyDown = false;
        }
        else if (e.Key == Windows.System.VirtualKey.Control)
        {
            dataContext.IsControlKeyDown = false;
        }
    }

    private void DropArea_DragOver(object sender, DragEventArgs e)
    {
        e.Handled = true;
        e.AcceptedOperation = DataPackageOperation.Copy;
        e.DragUIOverride.IsCaptionVisible = true;
        e.DragUIOverride.Caption = "Drop file here";
        e.DragUIOverride.IsContentVisible = true;
    }

    private async void DropArea_Drop(object sender, DragEventArgs e)
    {
        if (e.DataView.Contains(StandardDataFormats.StorageItems))
        {
            IReadOnlyList<IStorageItem> items = await e.DataView.GetStorageItemsAsync();

            List<string> filePaths = [];

            foreach (IStorageItem item in items)
            {
                if (item is StorageFile file && !string.IsNullOrWhiteSpace(file.Path))
                {
                    filePaths.Add(file.Path);
                }
            }

            eventBus.Publish(new AddFileCommand(filePaths));
        }
    }
}
